package com.example.mvvmdemo.home.paging;

import androidx.annotation.NonNull;
import androidx.paging.rxjava2.RxPagingSource;

import com.example.httplibrary.bean.ResultBean;
import com.example.mvvmdemo.home.api.DeviceApiService;
import com.example.mvvmdemo.utils.GsonUtil;

import org.jetbrains.annotations.NotNull;

import io.reactivex.Single;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

/**
 * created by tl
 * created at 2020/9/2
 */
public class ExamplePagingSource extends RxPagingSource<Integer, DeviceExceptionBean.ContentBean> {
    @NonNull
    private DeviceApiService mBackend;

    public ExamplePagingSource(@NonNull DeviceApiService backend) {
        mBackend = backend;
    }

    @NotNull
    @Override
    public Single<LoadResult<Integer, DeviceExceptionBean.ContentBean>> loadSingle(
            @NotNull LoadParams<Integer> params) {
        // Start refresh at page 1 if undefined.
        Integer nextPageNumber = params.getKey();
        if (nextPageNumber == null) {
            nextPageNumber = 1;
        }

        PageBean pageBean = new PageBean();
        pageBean.setPageNum(nextPageNumber);
        pageBean.setPageSize(30);
        String str = GsonUtil.objectToString(pageBean);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; " +
                "charset=utf-8"), str);

        return mBackend.getExceptionList(body)
                .subscribeOn(Schedulers.io())
                .map(this::toLoadResult)
                .onErrorReturn(LoadResult.Error::new);
    }

    private LoadResult<Integer, DeviceExceptionBean.ContentBean> toLoadResult(
            @NonNull ResultBean<DeviceExceptionBean> response) {
        return new LoadResult.Page<>(
                response.getData().getContent(),
                response.getData().getPageSize() - 1, // Only paging forward.
                response.getData().getPageSize() + 1,
                LoadResult.Page.COUNT_UNDEFINED,
                LoadResult.Page.COUNT_UNDEFINED);
    }
}
